package org.xxpay.mch.paydemo.ctrl;

import com.alibaba.fastjson.JSONObject;
import com.vladsch.flexmark.ext.tables.TablesExtension;
import com.vladsch.flexmark.html.HtmlRenderer;
import com.vladsch.flexmark.parser.Parser;
import com.vladsch.flexmark.parser.ParserEmulationProfile;
import com.vladsch.flexmark.util.ast.Node;
import com.vladsch.flexmark.util.options.MutableDataSet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.xxpay.core.common.constant.Constant;
import org.xxpay.core.common.constant.MchConstant;
import org.xxpay.core.common.constant.RetEnum;
import org.xxpay.core.common.domain.XxPayResponse;
import org.xxpay.core.common.vo.DBApplicationConfig;
import org.xxpay.mch.common.config.MainConfig;
import org.xxpay.mch.common.ctrl.BaseController;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.Arrays;

@RestController
@RequestMapping(Constant.MCH_CONTROLLER_ROOT_PATH + "/paydoc")
@PreAuthorize("hasRole('"+ MchConstant.MCH_ROLE_NORMAL+"')")
public class PayDocController extends BaseController {

    private static final Logger _log = LoggerFactory.getLogger(PayDocController.class);
    
    @Autowired
    private MainConfig mainConfig;

    /**
     * 接口文档- 下载demo
     * @param request
     * @return
     */
    @PreAuthorize("hasRole('"+ MchConstant.MCH_ROLE_NORMAL+"')")
    @RequestMapping(value = "/downloadDemo")
    @ResponseBody
    public ResponseEntity<?> downloadDemo(HttpServletRequest request) {
    	try {
    		_log.info("download ,userId={}, path={}",getUser().getId() , mainConfig.getDownloadDemoPath());
			File file = new File(mainConfig.getDownloadDemoPath());
			byte[] body = null;
			InputStream is = new FileInputStream(file);
			body = new byte[is.available()];
			is.read(body);
			HttpHeaders headers = new HttpHeaders();
			headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
			headers.setContentDispositionFormData("attachment", file.getName());
			HttpStatus statusCode = HttpStatus.OK;
			ResponseEntity<byte[]> entity = new ResponseEntity<byte[]>(body, headers, statusCode);
			is.close();
			return entity;
		} catch (FileNotFoundException e) {
			_log.error("FileNotFoundException error", e);
			return ResponseEntity.ok(XxPayResponse.build(RetEnum.RET_COMM_PARAM_ERROR));
		} catch (Exception e) {
			_log.error("Exception error", e);
			return ResponseEntity.ok(XxPayResponse.build(RetEnum.RET_COMM_UNKNOWN_ERROR));
		}
    }

	/**
	 * 获取接口文档
	 * @return
	 */
	@RequestMapping("/get")
	@ResponseBody
	public ResponseEntity<?> getDoc(HttpServletRequest request) throws IOException {
		JSONObject param = getJsonParam(request);
		String type = getStringRequired(param, "type");
		String content = commonService.sysConfigService.getValByCode(type);
		DBApplicationConfig dbConfig = commonService.sysConfigService.getDBApplicationConfig();
		content = content.replaceAll("\\{payUrl\\}", dbConfig.getConfig4PayUrl());
		MutableDataSet options = new MutableDataSet();
		options.setFrom(ParserEmulationProfile.MARKDOWN);
		options.set(Parser.EXTENSIONS, Arrays.asList(TablesExtension.create()));	// 解析表格
		Parser parser = Parser.builder(options).build();
		HtmlRenderer renderer = HtmlRenderer.builder(options).build();
		// 替换xxpay.org下文档图片路径（此处理不够完美，暂时方案）
		// 将![](/uploads/ 替换为 ![](http://docs.xxpay.org/uploads/
		content = content.replaceAll("\\!\\[\\]\\(/uploads/", "![](http://docs.xxpay.org/uploads/");
		Node document = parser.parse(content);
		String markdownHtml = renderer.render(document);  // "<p>This is <em>Sparta</em></p>\n"
		return ResponseEntity.ok(XxPayResponse.buildSuccess(markdownHtml));
	}

}
